﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Net.NetworkInformation;
using System.ComponentModel;
using System.IO.Ports;
using System.Windows.Media.Media3D;
using System.Diagnostics.Eventing.Reader;
using ScottPlot.Colormaps;
using System.Windows.Markup;
using ScottPlot;

namespace WpfWeight
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        BackgroundWorker backgroundWorker = new BackgroundWorker();
        public static string connstring = "server=192.168.1.21;uid=sa;pwd=aaar8001;database=aaar";
        public MainWindow()
        {
            InitializeComponent();


            port.BaudRate = 9600;
            port.Parity = Parity.None;
            port.StopBits = StopBits.One;
            port.DataBits = 8;
            port.Handshake = Handshake.None;
            port.RtsEnable = true;
            port.ReadTimeout = 10000;
            setlog("打开串口:");
         //   port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

            dg.ItemsSource = weight2BillNumbers;
            dgselected.ItemsSource = weight2Bilselected;

            backgroundWorker.WorkerSupportsCancellation = true;
            backgroundWorker.DoWork += BackgroundWorker_DoWork;
            setlog(   GetPhysicalAddress());
            //if ("00215D72DA82" != GetPhysicalAddress())
            //{
            //    MessageBox.Show("请和IT 沟通");
            //    this.Close();
            //}
        }
        SerialPort port = new SerialPort("COM3");
        private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                List<DateTime> dtlist = new List<DateTime>();
                List<double> listdb = new List<double>();
                List<byte> bytes = new List<byte>();
                while (!backgroundWorker.CancellationPending) { 
                
                    try
                    {


                  
                        if (!port.IsOpen)
                        {
                            port.Open();
                            setlog("opened");
                        }
               
                        port.DiscardInBuffer();
                     while (bytes.Count < 80  && !backgroundWorker.CancellationPending)
                    {
                       
                        byte b = (byte)port.ReadByte();
                       
                        bytes.Add(b);
                        //Byte[] btl = new Byte[128];
                        //port.Read(btl, 0, 128);
                        //bytes.AddRange(btl);    
                    }
                    setlog(ASCIIEncoding.ASCII.GetString(bytes.ToArray()));
                    port.Close();
                    int start = bytes.IndexOf(bytes.First(t => t == 0x0D));
                    byte[] lastdata = bytes.ToArray().Skip(start + 1).Take(17).ToArray();

                    //byte[] lastdata = { 0x02 , 0x3B, 0x30, 0x20, 0x30,
                    //    0x30, 0x30, 0x34, 0x34 , 0x35 , 0x30 , 0x30 , 0x30 , 0x30 , 0x30 , 0x30 , 0x0D };
                    var btslen = lastdata.Skip(1).Take(1).ToArray()[0];
                    var btsvalue = lastdata.Skip(4).Take(6).ToArray();
                    int b0 = Get8Bit(btslen, 0);
                    int b1 = Get8Bit(btslen, 1);
                    int b2 = Get8Bit(btslen, 2);


                    double zt = 1;
                    if (b0 == 0 && b1 == 0 && b2 == 0)
                    { zt = 100; }
                    if (b0 == 1 && b1 == 0 && b2 == 0)
                    { zt = 10; }
                    if (b0 == 0 && b1 == 1 && b2 == 0)
                    { zt = 1; }
                    if (b0 == 1 && b1 == 1 && b2 == 0)
                    { zt = 0.1; }
                    if (b0 == 0 && b1 == 0 && b2 == 1)
                    { zt = 0.01; }
                    if (b0 == 1 && b1 == 0 && b2 == 1)
                    { zt = 0.001; }
                    if (b0 == 0 && b1 == 1 && b2 == 1)
                    { zt = 0.0001; }
                    if (b0 == 1 && b1 == 1 && b2 == 1)
                    { zt = 0.00001; }




                    double weightcom = (int.Parse(ASCIIEncoding.ASCII.GetString(btsvalue).ToString()) * zt);


                    setlog("byte读重量:" + weightcom.ToString());
                        if (listdb.Count > 30)
                        {
                            listdb.RemoveAt(0);
                            dtlist.RemoveAt(0);
                        }
                        var weight = weightcom;
                        listdb.Add(weight);
                        dtlist.Add(DateTime.Now);
                        this.Dispatcher.Invoke(new Action(() =>
                    {
                        try
                        {
                         

                        
                            tbWeight.Text = weight.ToString();

                        
                            WpfPlot1.Plot.Clear();
                            var plt = WpfPlot1.Plot;

                            plt.Axes.DateTimeTicksBottom();

                            //   plt.Axes.SetLimitsY(10, 999);
                            double maxd = 20;
                            if (listdb.Max() > maxd)
                            {
                                maxd = listdb.Max()+10;
                            }
                            plt.Axes.SetLimitsY(-10, maxd);

                            WpfPlot1.Plot.Add.Scatter(dtlist, listdb, ScottPlot.Colors.Red);

                            WpfPlot1.Refresh();
                            setlog(System.DateTime.Now.ToShortTimeString()+"读重量:" + weight.ToString());



                        }
                        catch (Exception ex2) { setlog(ex2.ToString()); }
                    }));

                        System.Threading.Thread.Sleep(500);
                    }
                   catch (Exception ex) { setlog(ex.ToString());
                        break;
                    }
                    if (port.IsOpen)
                    {
                        port.Close();
                        setlog("Close");
                    }

                    setlog("Received data:  end " );

                }
                setlog("结束台作业");
            }
            catch (Exception ex)
            {
                setlog(ex.ToString()); }
        }

        private int Get8Bit(byte data, int index)
        {
            byte x = 1;
            switch (index)
            {
                case 0: { x = 0x01; } break;
                case 1: { x = 0x02; } break;
                case 2: { x = 0x04; } break;
                case 3: { x = 0x08; } break;
                case 4: { x = 0x10; } break;
                case 5: { x = 0x20; } break;
                case 6: { x = 0x40; } break;
                case 7: { x = 0x80; } break;
                default: { return 0; }
            }
            return (data & x) == x ? 1 : 0;
        }


        public ObservableCollection<Weight2billNumber> weight2Bilselected= new ObservableCollection<Weight2billNumber>();
        public ObservableCollection<Weight2billNumber> weight2BillNumbers = new ObservableCollection<Weight2billNumber>();
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try {
                if (tbSGK.Text.Length > 12)
                {
                    tbSGK.Text = tbSGK.Text.Substring( tbSGK.Text.IndexOf("DJ"));
                }
                else { MessageBox.Show("没有随工卡号"); return; }
                
                decimal weight;
                 decimal.TryParse(tbWeight.Text,out weight);
                if ((weight - (decimal)0.001)>0 && weight < 10000)
                {

                 
                
                    SqlDataAdapter SqlDataAdapter = new SqlDataAdapter("select   * from t_capp_m  where      ljmc like  '%搅拌器%'  and  billnumber = '" + tbSGK .Text + "' ", connstring);
                    try
                    {
                        var   ds = new DataSet();
                        SqlDataAdapter.Fill(ds, "Table0");
                        if (ds.Tables[0].Rows.Count ==0)
                        {
                            setlog("没有找到随工卡号" + tbSGK.Text);
                            MessageBox.Show("没有找到随工卡号");
                            return;
                        }

                        using (SqlConnection conn = new SqlConnection(connstring))

                        {

                            conn.Open();

                            // 你的代码
                            string queryString = "UPDATE t_capp_m SET weight = @weight  ,weight_time = getdate()   WHERE billnumber =@billnumber";

                            using (SqlCommand command = new SqlCommand(queryString, conn))

                            {

                                command.Parameters.AddWithValue("@weight", weight);

                                command.Parameters.AddWithValue("@billnumber", tbSGK.Text);

                                command.ExecuteNonQuery();

                            }
                            conn.Close();
                        }
                        ds.Clear();
                        SqlDataAdapter.Fill(ds, "Table0");
                        setlog("随工卡号重量" + ds.Tables[0].Rows[0]["billnumber"] + ":" + ds.Tables[0].Rows[0]["weight"].ToString());
                        weight2BillNumbers.Insert(0, new Weight2billNumber { weight = decimal.Parse(ds.Tables[0].Rows[0]["weight"].ToString()), 
                            billNumber = ds.Tables[0].Rows[0]["billnumber"].ToString() ,
                            ljmc = ds.Tables[0].Rows[0]["ljmc"].ToString() ,



                      ljth = ds.Tables[0].Rows[0]["ljth"].ToString()
                        });

                        
                    }
                    catch(Exception ex0)
                    {
                        MessageBox.Show("重量异常" + ex0.ToString());

                    }
                    finally
                    {
                        SqlDataAdapter.Dispose();
                       
                    }




                    Buttcheck_Click(null ,null );


                }
                else
                {
                    MessageBox.Show("重量异常"+ tbWeight.Text);
                }


            }
            catch (Exception ex) {
            
            MessageBox.Show(ex.Message);
            }

        }


        void setlog(string msg)
        {
            logtxt.Dispatcher.BeginInvoke(new Action(() => { 
            try
            {
                logtxt.Text = logtxt.Text + "\r\n";
                if (logtxt.Text.Length > 10000)
                {
                    logtxt.Text = logtxt.Text.Substring(5000);


                }
                logtxt.Text = logtxt.Text + msg;
                logtxt.ScrollToEnd();
            }catch { }
            }));
        }

        private void Buttcheck_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                weight2Bilselected.Clear();
                string sgkh = tbSGK.Text.Trim();
                if (string.IsNullOrEmpty(sgkh.Trim()) && string.IsNullOrEmpty(tbScbh.Text.Trim()))
                {
                    return;
                }
              
                  string sql = "select isnull(  weight , 0) weight  ,billnumber , ljmc ,ljth    from t_capp_m  where      ljmc like  '%搅拌器%'  and   scbh = '" + tbScbh.Text.Trim() + "'  order by billnumber";

                if (sgkh.Contains("DJ"))
                { sgkh = sgkh.Substring(sgkh.IndexOf("DJ")); }
                   if (sgkh.Length > 0 ) 
                {

                    sql = "select isnull(  weight , 0) weight  ,billnumber , ljmc ,ljth    from t_capp_m  where    billnumber  = '" + sgkh + "' AND   ljmc like  '%搅拌器%'     order by billnumber"; 
                }
                  

                     SqlDataAdapter SqlDataAdapter = new SqlDataAdapter(sql, connstring);
                    try
                    {
                        var ds = new DataSet();
                        SqlDataAdapter.Fill(ds, "Table0");
                     

                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        weight2Bilselected.Add( new Weight2billNumber
                        {
                            weight = decimal.Parse(dr["weight"].ToString()),
                            billNumber = dr["billnumber"].ToString(),
                            ljmc = dr["ljmc"].ToString(),



                            ljth = dr["ljth"].ToString()
                        });

                    }


                    }
                    catch
                    {

                    }
                    finally
                    {
                        SqlDataAdapter.Dispose();

                    }
             }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }
        public string GetPhysicalAddress()
        {
            NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface nic in interfaces)
            {
                if (nic.OperationalStatus == OperationalStatus.Up)
                {
                    return nic.GetPhysicalAddress().ToString();
                }
            }
            return null;
        }

        private void dgselected_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {try
            {

                if (dgselected.SelectedItem == null)
                { return; }
                Weight2billNumber weight2BillNumber = dgselected.SelectedItem as Weight2billNumber;
                tbSGK.Text = weight2BillNumber.billNumber;
            }catch { }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
           
        }

        private void BackgroundWork_DoWork(object sender, DoWorkEventArgs e)
        {
           
        }

     
        private void Window_Unloaded(object sender, RoutedEventArgs e)
        {


        }
        SerialPort mySerialPort = new SerialPort("COM3"); // COM端

      async   private void start_Click(object sender, RoutedEventArgs e)
        {
      

            if (!backgroundWorker.IsBusy)
            { backgroundWorker.RunWorkerAsync(); }
            setlog(" start:");
          
        }

        
   
        private void end_Click(object sender, RoutedEventArgs e)
        {
            if (backgroundWorker.IsBusy)
            { backgroundWorker.CancelAsync(); }
        }
    }
    public class Weight2billNumber
    { 
   
        
        public string billNumber { get; set;  }
        public string ljmc { get; set; }

        public string ljth { get; set; }


        public decimal weight { get; set; }


    }


}
